<?php

namespace app\api\controller\kami;

use app\common\controller\Api;
use app\common\library\AesEncrypt;
use think\Config;
use think\Env;

/**
 * 加解密接口
 */
class Aes extends Api
{
    protected $noNeedLogin = ['encrypt', 'decrypt'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 加密
     * @ApiMethod (POST)
     */
    public function encrypt()
    {
        $data = $this->request->param();
        if (!$data) {
            $this->error(__('Invalid parameters'));
        }
        $jsonStr = json_encode($data, JSON_UNESCAPED_UNICODE);
        $encryptData = AesEncrypt::encrypt($jsonStr, Env::get('server.aes_key'));
        if ($encryptData) {
            $this->success('加密成功', $encryptData);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 解密
     * @ApiMethod (POST)
     */
    public function decrypt()
    {
        $data = $this->request->getInput();
        if (!$data) {
            $this->error(__('Invalid parameters'));
        }
        $decryptedData = AesEncrypt::decrypt($data, Env::get('server.aes_key'));
        if (!$decryptedData) {
            $this->error(__('Decryption failed'), $decryptedData);
        }
        $params = json_decode($decryptedData, JSON_UNESCAPED_UNICODE);
        if ($params) {
            $this->success('解密成功', $params);
        } else {
            $this->error($this->auth->getError());
        }
    }
}
